# 利用公开数据实现高送转预期选股策略
# coding: utf-8

import tushare as ts

#基本面数据
basic = ts.get_stock_basics()

#行情和市值数据
hq = ts.get_today_all()


#当前股价,如果停牌则设置当前价格为上一个交易日股价
hq['trade'] = hq.apply(lambda x:x.settlement if x.trade==0 else x.trade, axis=1)

#分别选取流通股本,总股本,每股公积金,每股收益
basedata = basic[['outstanding', 'totals', 'reservedPerShare', 'esp']]

#选取股票代码,名称,当前价格,总市值,流通市值
hqdata = hq[['code', 'name', 'trade', 'mktcap', 'nmc']]

#设置行情数据code为index列
hqdata = hqdata.set_index('code')

#合并两个数据表
data = basedata.merge(hqdata, left_index=True, right_index=True)


# data.head(10)


#将总市值和流通市值换成亿元单位
data['mktcap'] = data['mktcap'] / 10000
data['nmc'] = data['nmc'] / 10000


#每股公积金>=5
res = data.reservedPerShare >= 2
#流通股本<=2亿
out = data.outstanding <= 2
#每股收益>=5毛
eps = data.esp >= 0.5
#总市值<100亿
mktcap = data.mktcap <= 100


allcrit = res & out & eps & mktcap
selected = data[allcrit]


df = selected[['name','trade', 'reservedPerShare', 'outstanding', 'esp', 'mktcap', 'nmc']]


df.sort_values('trade')


yg = ts.forecast_data(2016, 4)


yg.sort_values('range', ascending=False)


ygdata = yg.copy()


ygdata = ygdata.set_index('code')


ygs = basic.merge(ygdata, left_index=True, right_index=True)


ygs = ygs[['name_x', 'pe', 'outstanding', 'totals', 'reservedPerShare', 'esp', 'range']]


ygs[(ygs.outstanding <= 2) & (ygs.reservedPerShare>=3) & (ygs.esp >= 0.5)]